//
//  NetWorkHandler.m
//  Project
//
//  Created by dllo on 16/1/16.
//  Copyright © 2016年 刘旺辉. All rights reserved.
//

#import "NetWorkHandler.h"

#import "Reachability.h"
#import <CommonCrypto/CommonDigest.h>


@implementation NetWorkHandler

+ (void)networkingWithUrl:(NSString *)string comleteHandle:(void (^)(id, NSData *))block {
#pragma mark - 判断网络状态
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    if (isExistenceNetwork) {
        
        // 将字符串进行转码 (URL 中不能含有中文等字符 )
        
        NSString *temp = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:temp]];
        
        
        // session
        NSURLSession *session = [NSURLSession sharedSession];
        //
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            if (data) {
                
                // 该路径, 可以直接调用SDWebImage清除缓存的方法, 把该缓存清除掉
                NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
                NSString *behind = @".data";
                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                
                NSString *path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetWorkHandler md5HexDigest:string],behind]];
                
                [data writeToFile:path  atomically:YES];
                
                // 数据解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                // 调用 block
                // 回到主线程(GCD)
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    block(result, data);
                    
                });
                
            }
            
        }];
        
        [task resume];
        
        
        
    }else {
        NSLog(@"没有网络(断网)");
        NSString *cook = @"default/com.hackemist.SDWebImageCache.default/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        
        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetWorkHandler md5HexDigest:string],behind]];
        
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        if (data == nil) {
            return;
        } else {
            
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            block(result, data);
        }
    }
}
/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char *str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}

@end

